package com.fate.system.service.impl;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fate.framework.exception.KKException;
import com.fate.system.entity.EmailRecord;
import com.fate.system.mapper.EmailRecordMapper;
import com.fate.system.service.EmailRecordService;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

/**
 * 邮件发送记录Service实现
 *
 * @author EleAdmin
 * @since 2019-06-19 04:07:54
 */
@Service
public class EmailRecordServiceImpl extends ServiceImpl<EmailRecordMapper, EmailRecord>
    implements EmailRecordService {
  // 发件邮箱
  @Value("${spring.mail.username}")
  private String formEmail;

  @Resource private JavaMailSender mailSender;

  @Override
  public void sendTextEmail(String title, String content, String[] toEmails) {
    if (Arrays.stream(toEmails).anyMatch(Objects::isNull)) {
      return;
    }
    try {
      String s = new String(("顶小通" + " <" + formEmail + ">").getBytes(StandardCharsets.UTF_8));
      SimpleMailMessage message = new SimpleMailMessage();
      message.setFrom(s);
      message.setTo(toEmails);
      message.setSubject(title);
      message.setText(content);
      mailSender.send(message);
    } catch (Exception e) {
      throw new KKException("邮箱发送方法：sendTextEmail异常");
    }
  }

  @Override
  public void sendFullTextEmail(String title, String html, String[] toEmails)
      throws MessagingException {
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    helper.setFrom(formEmail);
    helper.setTo(toEmails);
    helper.setSubject(title);
    // 发送邮件
    helper.setText(html, true);
    mailSender.send(mimeMessage);
  }
}
